'use strict';
const Util = require('./util');
const Axios = require('axios');
const proxys = {};

async function pushProxy(platform, proxy) {
    proxys[platform] = proxys[platform] || [];
    proxys[platform].push(proxy);
}

const checkExpires = function(proxy, effectivetime = 5 * 60 * 1000) {
    const now = (new Date()).getTime();
    const pasttime = proxy.time + proxy.expiresIn;
    const result = pasttime > (now + effectivetime);
    return result;
};

async function popProxy(platform) {
    let proxyPlatform = proxys[platform] = proxys[platform] || [];
    let proxy = null;
    if (proxyPlatform.length <= 0) {
        await getProxyData(platform);
        proxyPlatform = proxys[platform] = proxys[platform] || [];
    }
    while (proxyPlatform.length > 0) {
        proxy = proxyPlatform.shift();
        const timeoutStatus = checkExpires(proxy);
        if (timeoutStatus) {
            break;
        }
    }
    if (!proxy) {
        return await popProxy(platform);
    }
    return proxy;
}


async function getProxyData(platform) {
    try {
        const res = await Axios({
            method: 'get',
            url: 'http://dps.kdlapi.com/api/getdps/?orderid=975469314753952&num=10&pt=1&sep=1&f_et=1',
        });
        const now = (new Date()).getTime();
        const trackIpArr = res.data.split('\r\n');
        for (const ipTime of trackIpArr) {
            let host = ipTime.split(',')[0].split(':');
            const port = host[1];
            host = host[0];
            const expiresIn = ipTime.split(',')[1];
            await pushProxy(platform, {
                port,
                host,
                expiresIn: parseInt(expiresIn) * 1000,
                time: now,
            });
        }
    } catch (e) {
        await Util.sleep(5000);
        await getProxyData(platform);
    }
}


module.exports = popProxy;